<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 路由分发控制，无验证访问
 * Class Home
 */
class Home extends Base_Controller {


	function __construct ()
	{
		parent::__construct();
        $this->load->library('form_validation');
        $this->load->model('smslog_m');
	}

	public function index()
	{
        //域名判断
        $host = $_SERVER['HTTP_HOST'];
        $get = $this->input->get();
        if(strstr($host,'wx')){
            //微信端
            if(isset($get['referee_id']) && !empty($get['referee_id'])){
                $this->session->set_userdata('referee_id', $get['referee_id']);
                redirect(site_url('wx/home/index?referee_id='.$get['referee_id']));
            }else{
                redirect(site_url('wx/home/index'));
            }
        }else if(strstr($host,'admin')){
            if($this->session->userdata('user_id')){
                //管理员端首页
                redirect(site_url('manage/home'));
            }else{
                //管理员端登录
                $data['top_memu'] = 'login';
                $data['viewmulu']=base_url('public/admin/');
                $this->load->view(X_URL.'login/login',$data);
            }
        }else{
            //微信端
            if(isset($get['referee_id']) && !empty($get['referee_id'])){
                $this->session->set_userdata('referee_id', $get['referee_id']);
                redirect(site_url('wx/home/index?referee_id='.$get['referee_id']));
            }else{
                redirect(site_url('wx/home/index'));
            }
        }

	}

    /**
     * 后台登录
     */
    public function admin_login()
    {
        if($this->auth->is_login())
        {
            redirect(site_url('manage/home'));
        }
        if($_POST && $this->validate_login_form()){
            $usernames = $this->input->post('username', TRUE);
            if(checkMobile($usernames)){
                $username = $this->user_m->get_username_by_utel($usernames);
                $username = $username['user_name'];
            }elseif(validateEmail($usernames)){
                $username = $this->user_m->get_username_by_uemail($usernames);
            }else{
                $username = $usernames;
            }
            if(!$this->user_m->check_ulock($username)){
                // 清楚登录session 重新去登录
                show_message('您的帐号已经被锁定！',site_url('/'));
                exit;
            }
            $userpass = $this->input->post('password',TRUE);
            $str = array(
                'user_name' => $username,
                'user_password' => $userpass
            );

            if ($this->user_m->login($str)) {
                // 用户组是否已经禁用
                $uid = $this->session->userdata('user_id');
                $userinfo=$this->user_m->get_user_by_user_id($uid);
                if(!$this->authGroup_m->is_user_group_able($userinfo['user_group'])){
                    $this->user_m->del_user_key_by_user_id($uid);
                    $this->session->unset_userdata('user_id');
                    setcookie('loveme', '', time() - 3600, '/', '', false, true);
                    $this->session->sess_destroy();
                    show_message('用户组已被禁用！',site_url('home/login'));
                    exit;
                }
                if($userinfo['user_group'] == 4){
                    $this->user_m->del_user_key_by_user_id($uid);
                    $this->session->unset_userdata('user_id');
                    setcookie('loveme', '', time() - 3600, '/', '', false, true);
                    $this->session->sess_destroy();
                    show_message('普通用户不能登录管理后台！',site_url('home/login'));
                    exit;
                }
                $dates = date('Ymd',time());
                $udates = date('Ymd',$userinfo['user_logtime']);
                //更新登陆次数
                $this->user_m->update_ulognum($uid);
                //更新最后登录时间
                $this->user_m->update_user($uid,array('user_logtime'=>time()));
                if($this->config->item('credit_login')>0 && $dates<>$udates){
                    $this->user_m->update_credit($uid,$this->config->item('credit_login'));
                }
                //经纬度
                $this->config->load('webapiset');
                $this_ip = get_onlineip();
                if(!empty($xy = $this->myclass->user_baidu($this->config->item('baidu_ip_ak'),4,$this_ip))){
                    $xy = explode(',',$xy);
                    $this->user_m->update_user($uid,array('user_lat'=>$xy[1],'user_lng'=>$xy[0]));
                }
                show_message('恭喜您，成功登陆本站！',site_url('manage/home'),1);
                exit;
            }else{
                show_message('抱歉哦，登陆本站失败！');
                exit;
            }
        }
        $data['viewmulu']=base_url('public/admin/');
        $this->load->view('manage/login/login',$data);
    }
    private function validate_login_form(){
        $this->form_validation->set_rules('username', '帐号' , 'trim|required|min_length[3]|xss_clean');
        $this->form_validation->set_rules('password', '密码' , 'trim|required|min_length[6]|max_length[18]');
        $this->form_validation->set_message('required', "%s 不能为空！");
        $this->form_validation->set_message('min_length', "%s 最小长度不少于 %s 个字符！");
        $this->form_validation->set_message('max_length', "%s 最大长度不多于 %s 个字符！");
        if ($this->form_validation->run() == FALSE){
            return FALSE;
        }else{
            return TRUE;
        }
    }
    public function logout ()
    {
        $this->auth->user_logout();
    }
    /**
     * 发送验证码逻辑
     */
    public function ajax_send_sms()
    {
        $mobile =$this->input->get("mobile");

        if(empty($mobile)){
            echo json_encode(['code'=>400,'msg' => '参数缺失']);exit();
        }
        if (!$this->verifyMobile($mobile)) {
            echo json_encode(['code'=>200,'msg' => '号码格式错误']);
            exit;
        }
        // 生成验证码
        $code = $this->creatCodeByRand();
        // 入库
        $data = array(
            'mobile'=>$mobile,
            'yzm'=>$code,
            'type'=>1,
            'createtime'=>date("Y-m-d H:i:s", time()),
        );
        if($this->smslog_m->add_sms_log($data)){
            //发送验证码
            $response = $this->send_sms_code($mobile, $code);
            // 返回
            if (isset($response->Code) && $response->Code == 'OK') {
                // 缓存
                $phoneCode = $this->phoneCodeArr($mobile);
                $phoneCode[$mobile] = ['code'=>$code, 'status'=>0];
                $this->session->set_userdata($mobile.'_info',$phoneCode);
                echo json_encode(['code' => 200, 'msg' => '发送成功']);exit();
            } else {
                echo json_encode(['code' => 400, 'msg' => '发送失败']);exit();
            }
        }else{
            echo json_encode(['code' => 400, 'msg' => '网络异常, 请稍后再试']);exit();
        }

    }

    /**
     * 查询缓存
     * @param $mobile
     * @return array|mixed
     */
    private function phoneCodeArr($mobile) {
        $info = $this->session->userdata($mobile."_info");
        if (!empty($info)) {
            return $info;
        }
        return [];
    }
    /**
     * 验证 手机验证码
     * @param  Int $mobile    手机号码
     * @param  Int $phoneCode 验证码
     * @return Boolean
     */
    private function verifyPhoneCode($mobile, $phoneCode) {
        $result = false;
        $phoneCodeArr = $this->phoneCodeArr($mobile);
        if (isset($phoneCodeArr[$mobile])) {
            if ($phoneCodeArr[$mobile]['code'] == $phoneCode) {
                $phoneCodeArr[$mobile]['status'] = 1;
                $this->session->set_userdata($mobile.'_info',$phoneCodeArr);
                $result = true;
            }
        }
        return $result;
    }
    /**
     * 验证手机号规则
     * @param $mobile
     * @return bool
     */
    private function verifyMobile($mobile) {
        $return = false;
        // 正则手机或固定电话
        $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
        $isMob = "/^1[3-5,7,8]{1}[0-9]{9}$/";
        if(preg_match($isMob, $mobile) || preg_match($isTel, $mobile)) {
            $return = true;
        }
        return $return;
    }
    /**
     * 生成验证码
     * @return string
     */
    private function creatCodeByRand(){
        $token = '';
        $len = 6;
        for ($i = 0; $i < $len; $i++)
            $token .= chr(mt_rand(48, 57));
        return $token;
    }

    /**
     * 短信验证码接口
     * @param $mobile 手机号码
     * @param $code 验证码
     * @param string $temp 短信模板
     * @param string $type 模板自定义变量
     * @return stdClass
     */
    public function send_sms_code($mobile, $code,$temp = 'SMS_110605015',$type = 'code') {

       $this->load->library('alisms');
       $response = $this->alisms->sendSms("顺势全网营销", $temp, $mobile, [ $type => $code]);
        return (object)['Code'=>"OK"];
       return $response;
    }

    public function language(){
        $lang =$this->input->get("lang");
        if(!empty($lang)){
            $uid = $this->session->userdata('user_id');
            $this->user_m->update_user($uid,['user_language'=>$lang]);
            redirect(site_url(W_URL."user/index"));
        }else{
            $this->load->view('language');
        }
    }


}
